package com.adwin.addcoin.repository.h5

import android.content.Context
import android.util.Log
import android.webkit.JavascriptInterface
import androidx.datastore.dataStore
import com.adwin.addcoin.AddCoinApplication
import com.adwin.addcoin.utils.FlowKeyUtils
import com.adwin.addcoin.utils.PersonalMessageUtils
import com.adwin.addcoin.utils.installRepost
import com.adwin.addcoin.utils.log
import com.cashbird.app.infra.utils.FlowBus
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONObject

class H5SendAppCommunication(val mContext:Context) {

    @JavascriptInterface
    fun getUserCoins():String{
        val obj = JSONObject();
        obj.put("coins",PersonalMessageUtils.userCoinsBean.value?.coinNum?:0)
        return obj.toString()
        "getUserCoins: ${obj.toString()}".log()
    }
    @JavascriptInterface
    fun reportEvent(repost:String){
        Log.d("reportEvent","repost:${repost}")
        val jsonArray = JSONArray(repost)

        for (item in 0 until jsonArray.length()) {
            val obj = jsonArray.getJSONObject(item)
            val event = obj.optString("event_name")
            obj.remove("event_name")
            MainScope().launch (Dispatchers.IO){
                mContext.installRepost(event,obj)
            }
        }
        "reportEvent: ${jsonArray.toString()}".log()

    }
    @JavascriptInterface
    fun finishActivity(){
        MainScope().launch {
            FlowBus.with<String>(FlowKeyUtils.finishActivity).post("")
        }
    }
    @JavascriptInterface
    fun getInviteCode():String{
        val obj = JSONObject()
        obj.put("code",PersonalMessageUtils.inviteCode)
        obj.put("inviteNum",PersonalMessageUtils.inviteNumber)
        obj.put("inviteCoins",PersonalMessageUtils.inviteCoins)
        "getInviteCode: ${obj.toString()}".log()
        return obj.toString()
    }

    @JavascriptInterface
    fun getToken():String = AddCoinApplication.token

}